package com.qiudao.basestudy.util.strategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Description: Bean工具类
 *  在非spring管理的类中获取spring注册的bean
 * @author: gdc
 * @date: 2020/3/14
 * @version 1.0
 */
@Component
public class BeanTool implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        if (applicationContext == null) {
            applicationContext = context;
        }
    }

    /**
     * 通过 name 获取实例对象
     * @param name          Bean Name
     * @return              Spring 注入的实例
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 通过具体的Class，获取其注入的实例对象
     * @param clazz         Class
     * @return              Spring 注入的实例
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

}